#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/6/11 14:15
# @Auther  : Frank
# @Email   : 550862872@qq.com
# @File    : views.py
# @Software: PyCharm


from django.shortcuts import render,redirect,HttpResponse
from utils import sqlheper
import pymysql
import json
'''
    查看班级信息
'''
def classs(request):
    class_list = sqlheper.get_list('select * from class order by title',[])
    return render(request,'classs.html',{'class_list':class_list})
def add_class(request):
    """
        添加班级信息
    :param request:
    :return:
    """
    if request.method == "GET":
        return render(request, 'add_class.html')
    else:
        v = request.POST.get('title')
        if len(v) > 0:
            sqlheper.modify('insert into class(title) values (%s)',[v])
            return redirect('/classs/')
        else:
            return render(request,'add_class.html',{'msg':'班级名称不能为空'})

def del_class(request):
    """
        删除班级信息
    :param request:
    :return:
    """
    nid = request.GET.get('nid')
    sqlheper.modify('delete from class where id = %s',[nid,])
    return redirect('/classs/')
'''
    修改班级信息
'''
def edit_class(request):
    if request.method == "GET":
        nid = request.GET.get('nid')
        result = sqlheper.get_one('select id,title from class where id =%s',[nid,])
        return render(request, 'edit_class.html',{'result':result})
    else:
        nid = request.GET.get('nid')
        title = request.POST.get('title')
        sqlheper.modify('update class set title = %s where id = %s',[title,nid])
        return redirect('/classs/')

def students(request):
    """
    学生列表
    :param request:封装了请求相关的信息
    :return:
    """
    student_list = sqlheper.get_list('SELECT student.id,student.name,class.title FROM student LEFT JOIN class ON student.class_id = class.id',[])
    class_list = sqlheper.get_list('select * from class',[])
    return render(request,'students.html',{'student_list':student_list,'class_list':class_list})

def add_student(request):

    if request.method == "GET":
        class_list = sqlheper.get_list('select * from class',[])
        return render(request, 'add_student.html', {'class_list': class_list})
    else:
        name = request.POST.get('name')
        class_id = request.POST.get('class_id')
        sqlheper.modify('insert into student(name,class_id) values (%s,%s)',[name,class_id])
        return redirect('/students/')

    """
        编辑学生信息
    :param request:
    :return:
    """
def edit_student(request):
    if request.method == "GET":
        nid = request.GET.get('nid')
        class_list = sqlheper.get_list("select id,title from class", [])
        current_student_info = sqlheper.get_one('select id,name,class_id from student where id=%s', [nid, ])
        return render(request, 'edit_student.html',
                          {'class_list': class_list, 'current_student_info': current_student_info})
    else:
        nid = request.GET.get('nid')
        name = request.POST.get('name')
        class_id = request.POST.get('class_id')
        sqlheper.modify('update student set name=%s,class_id=%s where id=%s', [name, class_id, nid, ])
        return redirect('/students/')

def del_student(request):
    """
        删除学生信息
    :param request:
    :return:
    """
    nid = request.GET.get('nid')
    sqlheper.modify('delete from student where id = %s',nid)
    return redirect('/students/')
'''
    对话框
'''
def modal_add_class(request):
    title = request.POST.get('title')
    if len(title) > 0:
        sqlheper.modify('insert into class(title) values (%s)',[title,])
        return HttpResponse('ok')
    else:
        '''
            页面不要刷新，提示错误信息
        '''
        return HttpResponse('班级标题不能为空')


'''
    对话框编辑班级信息
'''

def modal_edit_class(request):
    ret = {'status': True, 'message':None}
    try:
        nid = request.POST.get('nid')
        content = request.POST.get('content')
        sqlheper.modify('update class set title=%s where id=%s',[content,nid,])
    except Exception as e:
        ret['status'] = False
        ret['message'] = "处理异常"

    return HttpResponse(json.dumps(ret))
'''
    对话框编辑学生信息
'''
def modal_add_student(request):
    ret = {'status':True,'message':None}
    try:
        name = request.POST.get('name')
        class_id = request.POST.get('class_id')
        sqlheper.modify('insert into student(name,class_id) values (%s,%s)',[name,class_id,])
    except Exception as e:
        ret['status']=False
        ret['message']=str(e)

    return HttpResponse(json.dumps(ret))

def modal_edit_student(request):
    ret = {'status': True, 'message': None}
    try:
        nid = request.POST.get('nid')
        name = request.POST.get('name')
        class_id = request.POST.get('class_id')
        sqlheper.modify('update student set name=%s,class_id=%s where id=%s', [name, class_id, nid, ])
    except Exception as e:
        ret['status'] = False
        ret['message'] = str(e)
    return HttpResponse(json.dumps(ret))

# 多对多，以老师表展示
def teachers(request):
    # teacher_list = sqlheper.get_list('select id,name from teacher',[])
    teacher_list = sqlheper.get_list("""
    select teacher.id as tid,teacher.name,class.title from teacher
        LEFT JOIN teacher2class on teacher.id = teacher2class.teacher_id
        left JOIN class on class.id = teacher2class.class_id;
    """,[])
    result = {}
    for row in teacher_list:
        tid =row['tid']
        if tid in result:
            result[tid]['titles'].append(row['title'])
        else:
            result[tid] = {'tid': row['tid'],'name':row['name'],'titles': [row['title'],]}
    return render(request,'teachers.html',{'teacher_list':result.values()})

'''
    添加老师
'''
def add_teacher(request):
    if request.method == "GET":
        class_list = sqlheper.get_list('select id,title from class',[])
        return render(request,'add_teacher.html',{'class_list':class_list})
    else:
        name = request.POST.get('name')
        '''
            在老师表里边加入一条数据
        '''
        teacher_id = sqlheper.create('insert into teacher(name) values (%s)',[name,])

        class_ids = request.POST.getlist('class_ids')
        # 连接多次，提交多次
        # for cls_id in class_ids:
        #     sqlheper.modify('insert into teacher2class (teacher_id,class_id) values (%s,%s)',[teacher_id,class_ids])

        # 连接一次，提交多次
        # obj = sqlheper.SqlHeper()
        # for cls_id in class_ids:
        #     obj.modify('insert into teacher2class (teacher_id,class_id) values (%s,%s)',[teacher_id,class_ids])
        # obj.close()

        # 一次连接，一次提交
        data_list = []
        for cls_id in class_ids:
            temp = (teacher_id,cls_id,)
            data_list.append(temp)
        obj = sqlheper.SqlHeper()
        obj.multiple_modify('insert into teacher2class (teacher_id,class_id) values (%s,%s)',data_list)
        obj.close()

        print(name,class_ids)
        return redirect('/teachers/')
'''
    编辑老师
'''
def edit_teacher(request):

    if request.method == "GET":
        nid = request.GET.get('nid')
        obj = sqlheper.SqlHeper()
        teacher_info = obj.get_one('select id,name from teacher where id = %s',[nid,])
        class_id_list = obj.get_list('select class_id from teacher2class where teacher_id = %s',[nid])
        # 拿到class的id
        temp = []
        for i in class_id_list:
            temp.append(i['class_id'])
        class_list = obj.get_list('select id,title from class ',[])
        obj.close()
        #print({'当前老师信息':teacher_info,'当前班级id信息':class_id_list,'当前班级信息':class_list})

        return render(request,'edit_teacher.html',{
            'teacher_info':teacher_info,
            'class_id_list':temp,
            'class_list':class_list,
        })
    else:
        nid = request.GET.get('nid')
        name = request.POST.get('name')
        class_ids = request.POST.getlist('class_ids')

        #更新老师表
        obj = sqlheper.SqlHeper()
        obj.modify('update teacher set name = %s where id = %s',[name,nid,])
        #更新老师表和班级的关系表
        #1.先把老师和对应班级信息删除再添加
        #2.

        obj.modify('delete from teacher2class where teacher_id = %s',[nid,])

        data_list = []
        for cls_id in class_ids:
            temp = (nid, cls_id,)
            data_list.append(temp)
        obj = sqlheper.SqlHeper()
        obj.multiple_modify('insert into teacher2class (teacher_id,class_id) values (%s,%s)', data_list)
        obj.close()

        return redirect('/teachers/')

def get_all_class(request):
    import time
    time.sleep(2)
    obj = sqlheper.SqlHeper()
    class_list = sqlheper.get_list('select id,title from class',[])
    obj.close()
    return HttpResponse(json.dumps(class_list))

def modal_add_teacher(request):

    ret = {'status':True,'message':None}
    try:
        name = request.POST.get('name')
        class_id_list = request.POST.getlist('class_id_list')
        teacher_id = sqlheper.create('insert into teacher(name) values (%s)', [name, ])
        data_list = []
        for cls_id in class_id_list:
            temp = (teacher_id, cls_id,)
            data_list.append(temp)
        obj = sqlheper.SqlHeper()
        obj.multiple_modify('insert into teacher2class (teacher_id,class_id) values (%s,%s)', data_list)
        obj.close()
    except Exception as e:
        ret['status'] = False
        ret['message'] = '处理失败'

    return HttpResponse(json.dumps(ret))

def del_teacher(request):
    nid = request.GET.get('nid')
    obj = sqlheper.SqlHeper()
    obj.modify('delete from teacher where id = %s',[nid,])
    obj.modify('delete from class where id = %s',[nid])
    obj.close()
    return redirect('/teachers/')